﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using MIXer.Core.Contracts;
using MIXer.Customization;

namespace MIXer.Providers
{
    [PartCreationPolicy(CreationPolicy.Shared)]
    [Export(typeof(IConfigurationProvider))]
    public class FileConfigurationProvider : IConfigurationProvider
    {
        #region Constants
        private static string FILE_NAME = "mixer.cfg";
        #endregion

        #region Fields
        private Dictionary<string, string> _configs = new Dictionary<string, string>();
        private EventDelayAggregator _saveDelay;
        #endregion

        #region Constructors
        public FileConfigurationProvider()
        {
            Load();

            _saveDelay = new EventDelayAggregator(5000, () => // 5 seconds after last change the configs are saved
            {
                Save();
            });
        }
        #endregion

        #region Methods
        public T GetValueAs<T>(string key)
        {
            if (!_configs.ContainsKey(key))
            {
                var defaultValue = default(T);
                _configs.Add(key, defaultValue == null ? null : defaultValue.ToString());
            }

            var value = _configs[key];

            return (T)Convert.ChangeType(value, typeof(T));
        }
        public void SetValue<T>(string key, T value)
        {
            _saveDelay.Signal();
            var defaultValue = default(T);
            _configs[key] = value == null ? (defaultValue == null ? null : defaultValue.ToString()) : value.ToString();
        }
        public void Load()
        {
            var fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), FILE_NAME);

            if (File.Exists(fileName))
            {
                var lines = File.ReadAllLines(fileName);

                foreach (var str in lines)
                {
                    var valuePair = str.Split('=');
                    _configs.Add(valuePair[0], valuePair[1]);
                }

                Loaded = true;
            }
        }
        public void Save()
        {
            var fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), FILE_NAME);

            List<string> configs = new List<string>();

            foreach (var config in _configs)
            {
                configs.Add(String.Format("{0}={1}", config.Key, config.Value == null ? String.Empty : config.Value));
            }

            File.WriteAllLines(fileName, configs); 
        }
        #endregion

        #region Properties
        public bool Loaded { get; protected set; }
        #endregion
    }
}
